package com.example.dbbackupupload.utils;


import java.io.File;

/**
 * @Author Wlos
 * @Date 2025/3/14 10:54
 */
public class DbBackup {
    /**
     * 备份数据库db
     * @param root
     * @param pwd
     * @param dbName
     * @param backPath
     */
    public static void dbBackUp(String root,String pwd,String dbName,String backPath,String mysqldumpPath) throws Exception {
        File fileSql = new File(backPath);
        //创建备份sql文件
        if (!fileSql.exists()){
            fileSql.getParentFile().mkdirs();
            fileSql.createNewFile();
        }
        //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql
        StringBuilder sb = new StringBuilder();
        sb.append(mysqldumpPath);
        sb.append(" --single-transaction");
        sb.append(" -h127.0.0.1");
        sb.append(" -u"+root);
        sb.append(" -p"+pwd);
        sb.append(" "+dbName+" >");
        sb.append(backPath);
        System.out.println("cmd命令为："+ sb);
        Runtime runtime = Runtime.getRuntime();
        System.out.println("开始备份："+dbName);
        Process process = runtime.exec("cmd /c"+ sb);
        process.waitFor();
        System.out.println("备份成功!");
    }
}
